package com.findu.fragment;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.example.findu.R;
import com.example.findu.R.drawable;
import com.example.findu.R.id;
import com.example.findu.R.layout;
import com.findu.control.Home_dynamic_XListView;
import com.findu.control.Home_dynamic_XListView.IXListViewListener;
import com.findu.control.Public_title;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class Fragment_Conversation_home_1 extends  Fragment implements IXListViewListener {
	private View fragmentView;
	
	Public_title public_title;	//标题控制
	// 声明布局文件
	private View include_view;
	private Home_dynamic_XListView mListView;
	private SimpleAdapter mListAdapter;
	private Handler mHandler;
	private ArrayList<HashMap<String, Object>> mListData;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// 引入并得到view
		fragmentView = inflater.inflate(R.layout.fragment_conversation_home_1, container,false);
		
		
		// 初始化布局文件
		include_view = fragmentView.findViewById(R.id.fragment_conversation_page1_include);
		public_title = new Public_title(include_view);	// 新建工具类设置布局控件	
	
		public_title.setRighttImage(R.drawable.ic_launcher);
		public_title.setTextView("会话");
		
		mListData = new ArrayList<HashMap<String,Object>>();
		mListView = (Home_dynamic_XListView) fragmentView.findViewById(R.id.techan_xListView);
		mListView.setPullLoadEnable(true);
		mListAdapter = new SimpleAdapter(getActivity(), loadConversationsWithRecentChat()
				, R.layout.fragment_conversation_list_item
				, new String[] {"name", "img", "content", "time"}
				, new int[] {R.id.fragment_Conversation_Name, R.id.fragment_Conversation_Image, R.id.fragment_Conversation_Content, R.id.fragment_Conversation_Time});
		mListView.setAdapter(mListAdapter);
		mListView.setXListViewListener(this);
		mHandler = new Handler();
		return fragmentView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	}
	

	/**
	 * 获取所有会话
	 * 
	 * @param context
	 * @return
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        +	 */
	private List<HashMap<String, Object>> loadConversationsWithRecentChat() {
		// 获取所有会话，包括陌生人
		Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations();
		// 过滤掉messages size为0的conversation
		/**
		 * 如果在排序过程中有新消息收到，lastMsgTime会发生变化
		 * 影响排序过程，Collection.sort会产生异常
		 * 保证Conversation在Sort过程中最后一条消息的时间不变 
		 * 避免并发问题
		 */
		List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
		synchronized (conversations) {
			for (EMConversation conversation : conversations.values()) {
				if (conversation.getAllMessages().size() != 0) {
					//if(conversation.getType() != EMConversationType.ChatRoom){
						sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
					//}
				}
			}
		}
		try {
			// Internal is TimSort algorithm, has bug
			sortConversationByLastChatTime(sortList);
		} catch (Exception e) {
			e.printStackTrace();
		}

		mListData.clear();
		for (Pair<Long, EMConversation> sortItem : sortList) {
			EMConversation conversation = sortItem.second;
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("name", sortItem.second.getUserName());
			map.put("img", R.drawable.ic_launcher);
			map.put("content", conversation.getLastMessage().getBody().toString());
			map.put("time", new Date(conversation.getLastMessage().getMsgTime()).toString());
			mListData.add(map);
		}
		return mListData;
	}
	
	/**
	 * 根据最后一条消息的时间排序
	 * 
	 * @param usernames
	 */
	private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
		Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
			@Override
			public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

				if (con1.first == con2.first) {
					return 0;
				} else if (con2.first > con1.first) {
					return 1;
				} else {
					return -1;
				}
			}

		});
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime("刚刚");
	}
	
	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				loadConversationsWithRecentChat();
				mListView.setAdapter(mListAdapter);
				onLoad();
			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				loadConversationsWithRecentChat();
				mListAdapter.notifyDataSetChanged();
				onLoad();
			}
		}, 2000);
	}
}



